#!/usr/bin/env bash
set -e

RBENV_GEMSET_VERSION="0.5.9"

# Provide rbenv completions
if [ "$1" = "--complete" ]; then
  if [ -z "$2" ]; then
    echo "init"
    echo "active"
    echo "create"
    echo "delete"
    echo "file"
    echo "list"
    echo "version"
    exit
  else
    gemset_completion=1
    shift
  fi
fi

if [ "$1" = "version" ] || [ "$1" = "--version" ]; then
  if [ -n "$gemset_completion" ]; then
    exit
  fi
  echo "rbenv-gemset ${RBENV_GEMSET_VERSION}"
  echo "by Jamis Buck <jamis@jamisbuck.org>"
  echo "Currently maintained by Jeffrey 'jf' Lim <jfs.world@gmail.com>"
  echo
  echo "http://github.com/jf/rbenv-gemset"
  exit
fi

resolve_link() {
  $(type -p greadlink readlink | head -1) $1
}

abs_dirname() {
  local cwd="$(pwd)"
  local path="$1"

  while [ -n "$path" ]; do
    cd "${path%/*}"
    local name="${path##*/}"
    path="$(resolve_link "$name" || true)"
  done

  pwd
  cd "$cwd"
}

bin_path="$(abs_dirname "$0")"
export PATH="${bin_path}:$PATH"

if [ -z "$RBENV_GEMSET_SYSTEM_ROOT" ]; then
  export RBENV_GEMSET_SYSTEM_ROOT="/usr/local/share/ruby-gemsets"
fi

command="$1"
command_path="$(command -v "rbenv-gemset-$command" || true)"

if [ -z "$command_path" ]; then
  { echo "version ${RBENV_GEMSET_VERSION}"
    echo "rbenv gemset [command] [options]"
    echo
    echo "possible commands are:"
    echo "  active"
    echo "  create [version] [gemset]"
    echo "  delete [version] [gemset]"
    echo "  file"
    echo "  init [gemset]"
    echo "  list"
    echo "  version"
    echo
    echo "For full documentation, see: https://github.com/jf/rbenv-gemset#readme"
  } >&2
  exit 1
fi

shift
if [ -n "$gemset_completion" ] && grep -i "^# provide rbenv completions" "$command_path" >/dev/null; then
  exec "$command_path" --complete "$@"
elif [ -z "$gemset_completion" ]; then
  exec "$command_path" "$@"
fi
